#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os,sys,time,re
from apscheduler.scheduler import Scheduler
from Tasker import Tasker
from wwpy.util.Daemon import Daemon

global sched
sched=Scheduler(daemonic=False)

class Sched(Daemon):
    
    def __init__(self,interval=300,**kwargs):
        super(Sched,self).__init__(**kwargs)
        self.interval=interval
        self.jobs={}
        self.tasker=Tasker()
        self.tasks=self.tasker.tasks
        self.add_tasks(self.tasks)
        
    def add(self,task):
        job_id=task.get('id')
        timer=task.get('timer')
        minute,hour,day,month,day_of_week=re.split(r'\s+',timer)
        job=lambda task:self.tasker.do_task(task)
        self.jobs[job_id]=job
        sched.add_cron_job(job,minute=minute,hour=hour,day=day,day_of_week=day_of_week,args=[task])
        
    def add_tasks(self,tasks):
        for task_id,task in tasks.iteritems():
            self.add(task)
        
    def remove(self,task):
        job_id=task.get('id')
        job=self.jobs[job_id]
        sched.unschedule_func(job)
        self.jobs.pop(job_id)
        
    def remove_tasks(self,tasks):
        for task_id,task in tasks.iteritems():
            self.remove(task)
            
    def watch(self):
        try:
            sys.stdout.write('I am being watched.\n')
            sys.stdout.flush()
            current_tasks=self.tasker.tasks
            for cur_task_id,cur_task in current_tasks.iteritems():
                if cur_task_id not in self.tasks:
                    self.add(cur_task)
            for task_id,task in self.tasks.iteritems():
                if task_id not in current_tasks:
                    self.remove(task)
            self.tasks=current_tasks
        except Exception as msg:
            sys.stdout.write(str(msg))
            sys.stdout.flush()
        
    def run(self,*args,**kwargs):
        sched.start()
        while True:
            self.watch()
            time.sleep(self.interval)
        
    def start(self):
        self.start_daemon()
        
    def stop(self,wait=None):
        if wait is not None:
            time.sleep(wait)
        sched.shutdown()
        self.stop_daemon()
        
    def restart(self):
        self.stop()
        self.start()
        
if __name__ == '__main__':
    s=Sched(interval=60)
    s.start()
    s.stop(600)